<?php


namespace App\Http\Api\Controllers;


use App\Admin\Repositories\CoSchool;
use App\Library\JsonData;
use App\Models\CoAgreement;
use App\Models\CoAreas;
use App\Models\CoCargoType;
use App\Models\CoDistributionType;
use App\Models\CoExpress;
use App\Models\CoImg;
use App\Models\CoOrder;
use App\Models\CoRotation;
use App\Models\CoSchoolBuilding;
use App\Models\CoSchoolExpress;
use App\Models\CoSchoolName;
use App\Models\CoSchoolTime;
use App\Models\CoWeight;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class IndexController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new CoRotation();
    }

    /**
     * 获取轮播广告
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_rotation(Request $request){
        $school_id = intval($request->get('school_id',0));
        if(empty($school_id)){
            return JsonData::error('学校错误','',500);
        }
        $data = CoRotation::where('status',1)
            ->where('school_id',$school_id)
            ->orderBy("sort","asc")//倒序
            ->limit(5)
            ->get();
        if(!empty($data)){
            $data = $data->toArray();
            foreach ($data as $k=>$v){
                if(!empty($v['icon'])){
                    $v['icon'] = 'http://'.$_SERVER['SERVER_NAME'].'/uploads/'.$v['icon'];
                }
                $data[$k] = $v;
            }
        }
        return JsonData::success('返回成功',$data,200);
    }


    /**
     * 定位匹配学校 默认匹配5个
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_school(Request $request){
        try {
            $credentials      = $request->all();
            $validator = Validator::make($credentials, [
                'lat' => 'required',
                'lng' => 'required',
            ]);
            if ($validator->fails()) {
                return JsonData::error('参数错误','',500);
            }
            $lat = $request->lat;
            $lng = $request->lng;
            $data = DB::select("select id,name,seat_time,stop_time from co_school where lat>($lat-1) and lat <($lat+1) and lng>($lat-1) and lng<('104.03851836919785'+1) and status =1 order by ACOS(SIN(($lat*3.1415)/180)*SIN((lat*3.1415)/180)+COS(($lat * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(($lng* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc limit 10");
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }

    /**
     * 学校楼栋类型
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_school_name(Request $request){
        try {
            $school_id = intval($request->get('school_id',0));
            if(empty($school_id)){
                return JsonData::error('学校错误','',500);
            }
            $data = CoSchoolName::where('co_school_building.status',1)
                ->join('co_school_building','co_school_building.school_name_id','=','co_school_name.id')
                ->select('co_school_name.*')
                ->where(['co_school_building.school_id'=>$school_id,'co_school_building.status'=>1])
                ->distinct()
                ->get();
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }

    /**
     * 获取某个学校的某个类型的楼栋名
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_school_building(Request $request){
        try {
            $school_name_id = intval($request->get('school_name_id'));
            if (empty($school_name_id)) {
                return JsonData::error('类型错误','',500);
            }
            $school_id = intval($request->get('school_id',0));
            if(empty($school_id)){
                return JsonData::error('学校错误','',500);
            }
            $data = CoSchoolBuilding::where('status',1)
                ->where('school_name_id',$school_name_id)
                ->where(['school_id'=>$school_id])
                ->select('id','title','up_floor_Price','no_floor_Price')
                ->distinct()
                ->get();
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }

    /**
     * 获取重量参数
     * @param Request $request
     */
    public function get_weight(Request $request){
        try {
            $school_id = intval($request->get('school_id',0));
            if(empty($school_id)){
                return JsonData::error('学校错误','',500);
            }
            $distribution_type = intval($request->get('distribution_type',1));
            if(!in_array($distribution_type,[1,2])){
                return JsonData::error('配送方式错误','',500);
            }
            $data = CoWeight::where('status',1)
                ->where('school_id',$school_id)
                ->where('distribution_type',$distribution_type)
                ->select('id','name','sort','price')
                ->orderBy("sort","asc")//倒序
                ->get();
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }

    }


    /**
     * 配送方式
     */
    public function get_distribution(){
        try {
            $data = CoDistributionType::where('status',1)
                ->select('id','name','sort','price')
                ->orderBy("sort","asc")//倒序
                ->paginate(10);
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }

    /**
     * 获取物品类型
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_cargo(){
        $data = CoCargoType::where('status',1)
            ->select('id','name','sort')
            ->orderBy("sort","asc")//倒序
            ->get();
        return JsonData::success('返回成功',$data,200);
    }


    /**
     * 获取省市区信息
     */
    public function get_address(Request $request){
       $id =  $request->get('id',0);
       $data = CoAreas::where('pid',$id)->select('id','name')->get();
       return JsonData::success('返回成功',$data,200);
    }

    /**
     * 获取协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_agreement(Request $request){
        $type =  $request->get('type',1);
        if($type==1){
            $data = CoAgreement::where('type',1)->value('text');
        }else{
            $data = CoAgreement::where('type',2)->value('text');
        }
        return JsonData::success('返回成功',$data,200);
    }

    /**
     * @param Request $request
     */
    public function get_time(Request $request){
        try {
            $school_id =  intval($request->get('school_id',0));
            if(empty($school_id)){
                return JsonData::error('参数错误','',500);
            }
            $school = \App\Models\CoSchool::where('id',$school_id)->first();
            if(empty($school)){
                return JsonData::error('学校不存在','',500);
            }
            $info = CoSchoolTime::where('school_id',$school_id)->select('seat_time','stop_time')->get();
            if(empty($info)){
                return JsonData::error('未配置时间','',500);
            }
            $time = $info->toArray();
            $data = [];
            foreach ($time as $k=>$v){
                $data[] = date("H:i", strtotime($v['seat_time'])).'-'.date("H:i", strtotime($v['stop_time']));
            }
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }

    }

    /**
     * 学校快递点
     */
    public function school_express(Request $request){
        try {
            $school_id = intval($request->get('school_id'));
            if(empty($school_id)){
                return JsonData::success('参数错误',$school_id,500);
            }
            $data =[];
            if(isset($this->user_info->id) && $this->user_info->id >0){
                //查询用户上次使用的地址
                $pick_address =CoOrder::where('co_order.user_id',$this->user_info->id)
                    ->where('co_order.school_id',$school_id)
                    ->join('co_order_express','co_order_express.order_no','=','co_order.order_no')
                    ->select('co_order_express.pick_address')
                    ->first();
                if($pick_address){
                    $data[] =['id'=>0,'name'=>$pick_address];
                }
            }
            $data_list = CoSchoolExpress::where('school_id',$school_id)
                ->where('status',1)
                ->select('id','name')
                ->get();
            if(!empty($data)){
                $data = array_merge_recursive($data,$data_list);
            }else{
                $data = $data_list;
            }
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }

    }

    /**
     * 获取学校楼栋名称列表
     */
    public function get_list(Request $request){
        try {
            $school_id = intval($request->get('school_id'));
            if(empty($school_id)){
                return JsonData::success('参数错误',$school_id,500);
            }
            $data = CoSchoolBuilding::where('school_id',$school_id)
                ->where('status',1)
                ->select('id','title as name')
                ->get();
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }
    }

    /**
     * 获取快递公司列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_express(){
        try {
            $data = CoExpress::where('status','=',1)->orderBy('sort')->select('id','name','sort')->get();
            return JsonData::success('返回成功',$data,200);
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(), '', 500);
        }

    }

    /**
     * 订单加急比例
     */
    public function order_ratio(){
        $data =sys_config('order_ratio');
        return JsonData::success('返回成功',$data,200);
    }

    /**
     * 获取系统配置
     */
    public function get_config(){
        $data['service_time'] =sys_config('service_time');
        $data['telephone'] =sys_config('telephone');
        return JsonData::success('返回成功',$data,200);
    }

    /**
     * 首页图片
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_img(){
        $data = CoImg::where('id',1)->value('url');
        $data = 'http://'.$_SERVER['SERVER_NAME'].'/uploads/'.$data;
        return JsonData::success('返回成功',$data,200);
    }
}
